package com.olive.config;

import org.springframework.http.HttpMethod;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import com.olive.model.JwtAuthenticationToken;

import reactor.core.publisher.Mono;

@Component
public class CustomReactiveAuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {

	@Override
	public Mono<AuthorizationDecision> check(Mono<Authentication> authentication,
			AuthorizationContext authorizationContext) {
		// 获取当前请求的URL
		ServerWebExchange exchange = authorizationContext.getExchange();
		String path = exchange.getRequest().getPath().value();
		// 获取当前请求方法
		HttpMethod method = exchange.getRequest().getMethod();
		if (method == null || !StringUtils.hasText(path)) {
			System.out.println("CustomReactiveAuthorizationManager: cant not find http method in the request");
			throw new RuntimeException("CustomReactiveAuthorizationManager fail");
		}

		return authentication.map(token -> authorization(method.name(), path, (JwtAuthenticationToken) token));
	}

	/**
	 * 校验资源是否有权限
	 * 
	 * @param method
	 * @param path
	 * @param token
	 * @return
	 */
	private AuthorizationDecision authorization(String method, String path, JwtAuthenticationToken token) {
		// String appId = token.getAppId();
		//// 校验app是否可用
		// clientAuthorization.authorization(appId);
		//// scope权限校验
		// Scope scope = scopeAuthorization.authorization(appId, method, path,
		// token.getGrantedAuthorities());
		//// open api白名单校验
		// if (StringUtils.isNotBlank(token.getAccount())) {
		// openApiAccessListAuthorization.authorization(token, scope);
		// }

		return new AuthorizationDecision(true);
	}
}